package net.prasenjit.test.webservice.exception;

import org.apache.ws.security.WSSecurityException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.endpoint.AbstractEndpointExceptionResolver;
import org.springframework.ws.soap.*;

import javax.xml.namespace.QName;

public class ExceptionResolver extends AbstractEndpointExceptionResolver {

    @Override
    protected boolean resolveExceptionInternal(MessageContext messageContext, Object endpoint, Exception ex) {
        SoapMessage response = (SoapMessage) messageContext.getResponse();
        SoapBody body = response.getSoapBody();
        SoapFault fault = body.addServerOrReceiverFault(ex.getLocalizedMessage(), LocaleContextHolder.getLocale());
        SoapFaultDetail detail = fault.addFaultDetail();
        if (ex.getCause() instanceof WSSecurityException) {
            SoapFaultDetailElement detailMessage = detail.addFaultDetailElement(new QName("detailMessage"));
            detailMessage.addText(ex.getCause().getCause().getMessage());
        }
        return true;
    }

}
